"use client"

import React from "react"

import { useState, useRef, useEffect } from "react"
import { View, Text, StyleSheet, TouchableOpacity, Animated as RNAnimated, Platform, Dimensions } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import {
    ArrowLeft,
    List,
    BookmarkPlus,
    ChevronRight,
    ChevronLeft,
    Bookmark,
    Lightbulb,
    Settings,
} from "lucide-react-native"
import { useRouter, useLocalSearchParams } from "expo-router"
import { theme } from "../constants/theme"
import { WordListModal } from "../components/practices/WordListModal"
import { SplitSpellCard } from "../components/practices/SplitSpellCard"
import { NaturalReadingCard } from "../components/practices/NaturalReadingCard"
import { LetterSpellCard } from "../components/practices/LetterSpellCard"
import { ProgressBar } from "../components/practices/ProgressBar"
import { CollectionModal } from "../components/learning/CollectionModal"
import { WordCardContent } from "../components/unit/WordCardContent"
import { LearningSettingsModal, type LearningSteps } from "../components/practices/LearningSettingsModal"
import { StepsIndicator } from "../components/ui/StepsIndicator"
import { ReadingCard } from "../components/practices/ReadingCard"
import { ChoiceCard } from "../components/practices/ChoiceCard"

// 获取屏幕宽度
const { width, height } = Dimensions.get("window")
const isTablet = width > 768

// 模拟的练习数据
const PRACTICE_DATA = [
    {
        id: "1",
        word: "formulation",
        phonetic: "/fɔːmjuˈleɪʃ(ə)n/",
        type: "n",
        meaning: "公式化；阐述方式；规划；配方",
        parts: ["for", "mu", "la", "tion"],
        syllables: ["for", "mu", "la", "tion"],
        phoneticSyllables: ["/f/", "/ɔː/", "/r/", "/m/", "/ju/", "/l/", "/eɪ/", "/ʃ/", "/ə/", "/n/"],
        status: "new", // new, learning, mastered
        favorite: false,
        wordType: "keyWords", // 添加这一行，表示这是重点词
        meanings: ["公式化；阐述方式", "规划；配方"],
        examples: [
            {
                en: "He chose a milder formulation.",
                cn: "他选择了一种更温和的表述方式。",
            },
        ],
        etymology: {
            parts: [
                { text: "form", meaning: "形式" },
                { text: "ulate", meaning: "使...化" },
                { text: "ion", meaning: "名词后缀" },
            ],
            explanation: "form(形式) + ulate(使...化) + ion(名词后缀) = 公式化",
        },
        naturalReadingData: [
            { letter: "f", phonetic: "/f/", color: "#4B7FE5" },
            { letter: "o", phonetic: "/ɔː/", color: "#FF6B6B" },
            { letter: "r", phonetic: "/r/", color: "#4B7FE5" },
            { letter: "m", phonetic: "/m/", color: "#4B7FE5" },
            { letter: "u", phonetic: "/ju/", color: "#FF6B6B" },
            { letter: "l", phonetic: "/l/", color: "#4B7FE5" },
            { letter: "a", phonetic: "/eɪ/", color: "#FF6B6B" },
            { letter: "t", phonetic: "/t/", color: "#4B7FE5" },
            { letter: "i", phonetic: "/ɪ/", color: "#FF6B6B" },
            { letter: "o", phonetic: "/ə/", color: "#FF6B6B" },
            { letter: "n", phonetic: "/n/", color: "#4B7FE5" },
        ],
        options: [
            { id: "a", text: "公式化；阐述方式", correct: true },
            { id: "b", text: "形成；构成", correct: false },
            { id: "c", text: "配方；处方", correct: false },
            { id: "d", text: "规则；法规", correct: false },
        ],
        phonemes: [
            { letter: "for", sound: "/fɔːr/" },
            { letter: "mu", sound: "/mju/" },
            { letter: "la", sound: "/leɪ/" },
            { letter: "tion", sound: "/ʃən/" },
        ],
    },
    {
        id: "2",
        word: "favoritism",
        phonetic: "/ˈfeɪvərɪtɪzəm/",
        type: "n",
        meaning: "偏爱；偏袒；徇私",
        parts: ["fa", "vor", "i", "tism"],
        syllables: ["fa", "vor", "i", "tism"],
        phoneticSyllables: ["/f/", "/eɪ/", "/v/", "/ə/", "/r/", "/ɪ/", "/t/", "/ɪ/", "/z/", "/ə/", "/m/"],
        status: "learning",
        favorite: true,
        wordType: "recognition", // 添加这一行，表示这是需会认词
        meanings: ["偏爱；偏袒；徇私"],
        examples: [
            {
                en: "The teacher was accused of favoritism.",
                cn: "这位老师被指责有偏袒行为。",
            },
        ],
        etymology: {
            parts: [
                { text: "favor", meaning: "偏爱" },
                { text: "ite", meaning: "...的" },
                { text: "ism", meaning: "主义；行为" },
            ],
            explanation: "favor(偏爱) + ite(...的) + ism(行为) = 偏袒行为",
        },
        naturalReadingData: [
            { letter: "f", phonetic: "/f/", color: "#4B7FE5" },
            { letter: "a", phonetic: "/eɪ/", color: "#FF6B6B" },
            { letter: "v", phonetic: "/v/", color: "#4B7FE5" },
            { letter: "o", phonetic: "/ə/", color: "#FF6B6B" },
            { letter: "r", phonetic: "/r/", color: "#4B7FE5" },
            { letter: "i", phonetic: "/ɪ/", color: "#FF6B6B" },
            { letter: "t", phonetic: "/t/", color: "#4B7FE5" },
            { letter: "i", phonetic: "/ɪ/", color: "#FF6B6B" },
            { letter: "s", phonetic: "/z/", color: "#4B7FE5" },
            { letter: "m", phonetic: "/əm/", color: "#4B7FE5" },
        ],
        options: [
            { id: "a", text: "偏爱；偏袒", correct: true },
            { id: "b", text: "喜爱；热爱", correct: false },
            { id: "c", text: "特权；优待", correct: false },
            { id: "d", text: "歧视；偏见", correct: false },
        ],
        phonemes: [
            { letter: "fa", sound: "/feɪ/" },
            { letter: "vor", sound: "/vər/" },
            { letter: "i", sound: "/ɪ/" },
            { letter: "tism", sound: "/tɪzəm/" },
        ],
    },
    {
        id: "3",
        word: "turbine",
        phonetic: "/ˈtɜːbaɪn/",
        type: "n",
        meaning: "涡轮",
        parts: ["tur", "bine"],
        syllables: ["tur", "bine"],
        phoneticSyllables: ["/t/", "/ɜː/", "/b/", "/aɪ/", "/n/"],
        status: "new",
        favorite: false,
        wordType: "keyWords", // 添加这一行，表示这是重点词
        meanings: ["涡轮", "涡轮机"],
        examples: [
            {
                en: "Wind turbines generate electricity.",
                cn: "风力涡轮机发电。",
            },
        ],
        etymology: {
            parts: [
                { text: "turbo", meaning: "旋转" },
                { text: "ine", meaning: "名词后缀" },
            ],
            explanation: "turbo(旋转) + ine(名词后缀) = 涡轮",
        },
        naturalReadingData: [
            { letter: "t", phonetic: "/t/", color: "#5B8EF4" },
            { letter: "ur", phonetic: "/ɜː/", color: "#FF9500" },
            { letter: "b", phonetic: "/b/", color: "#5B8EF4" },
            { letter: "ine", phonetic: "/aɪn/", color: "#34C759" },
        ],
        options: [
            { id: "a", text: "涡轮", correct: true },
            { id: "b", text: "发动机", correct: false },
            { id: "c", text: "引擎", correct: false },
            { id: "d", text: "螺旋桨", correct: false },
        ],
        phonemes: [
            { letter: "tur", sound: "/tɜː/" },
            { letter: "bine", sound: "/baɪn/" },
        ],
    },
]

// 单词状态
type WordStatus = "new" | "learning" | "mastered"

// 步骤映射
const STEP_COMPONENTS = {
    学: 0,
    读: 1,
    听: 1, // 听和读使用相同的组件
    选: 2,
    拆分: 3,
    拼读: 4,
    拼写: 5,
}

export default function IntegratedLearningScreen() {
    const router = useRouter()
    const params = useLocalSearchParams()
    const [currentWordIndex, setCurrentWordIndex] = useState(0)
    const [currentStep, setCurrentStep] = useState(0)
    const [listModalVisible, setListModalVisible] = useState(false)
    const [wordStatus, setWordStatus] = useState<WordStatus>("new")
    const [isFavorite, setIsFavorite] = useState(false)
    const [collectionModalVisible, setCollectionModalVisible] = useState(false)
    const [hideStatusBar, setHideStatusBar] = useState(false) // 控制是否隐藏页面底部状态栏
    const [isChangingWord, setIsChangingWord] = useState(false) // 控制是否正在切换单词
    const [isFromPlan, setIsFromPlan] = useState(true)
    const [settingsModalVisible, setSettingsModalVisible] = useState(false)
    const [learningSteps, setLearningSteps] = useState<LearningSteps>({
        keyWords: ["学", "读", "选", "拆分", "拼读", "拼写"],
        recognition: ["学", "读", "选"],
    })
    const [activeMode, setActiveMode] = useState<"keyWords" | "recognition">("keyWords")

    // 学习步骤状态
    const [isPlaying, setIsPlaying] = useState(false)
    const [isSlowPlaying, setIsSlowPlaying] = useState(false)
    const [isRecording, setIsRecording] = useState(false)
    const [recordingDuration, setRecordingDuration] = useState(0)
    const recordingTimer = useRef<NodeJS.Timeout | null>(null)
    const recordingPulse = useRef(new RNAnimated.Value(1)).current
    const scoreScale = useRef(new RNAnimated.Value(0)).current
    const [score, setScore] = useState<number | null>(null)
    const [hasRecording, setHasRecording] = useState(false)
    const [allWordsCompleted, setAllWordsCompleted] = useState(false)

    // 选择步骤状态
    const [selectedOption, setSelectedOption] = useState<string | null>(null)
    const [isCorrect, setIsCorrect] = useState<boolean | null>(null)
    const [showFeedback, setShowFeedback] = useState(false)
    const fadeAnim = useRef(new RNAnimated.Value(1)).current
    const scaleAnim = useRef(new RNAnimated.Value(1)).current
    const feedbackAnim = useRef(new RNAnimated.Value(0)).current
    const correctAnim = useRef(new RNAnimated.Value(1)).current
    const pulseAnim = useRef(new RNAnimated.Value(1)).current

    // 拆分拼写状态
    const [selectedParts, setSelectedParts] = useState<string[]>([])
    const [showHint, setShowHint] = useState(false)
    const slotsOpacity = useRef(new RNAnimated.Value(1)).current

    // 自然拼读状态
    const [hintState, setHintState] = useState(0)
    const contentOpacity = useRef(new RNAnimated.Value(1)).current
    const wordOpacity = useRef(new RNAnimated.Value(0)).current

    // 字母拼写状态
    const [userInput, setUserInput] = useState("")
    const [feedbackState, setFeedbackState] = useState<"none" | "correct" | "incorrect">("none")

    // 反馈状态
    const [feedback, setFeedback] = useState<{ type: "success" | "error" | null; message: string }>({
        type: null,
        message: "",
    })

    // 动画值 - 使用RNAnimated代替react-native-reanimated
    const slideAnim = useRef(new RNAnimated.Value(0)).current
    const cardOpacity = useRef(new RNAnimated.Value(1)).current

    // 当前单词
    const currentWord = PRACTICE_DATA[currentWordIndex]

    // 初始化状态
    // 修改初始化状态的useEffect部分，确保根据单词类型正确设置activeMode
    useEffect(() => {
        // 设置初始状态
        if (!isChangingWord) {
            setWordStatus(currentWord.status)
            setIsFavorite(currentWord.favorite)

            // 根据单词状态设置学习模式
            if (isFromPlan) {
                // 如果单词有 wordType 属性，根据它来设置 activeMode
                if (currentWord.wordType === "recognition") {
                    setActiveMode("recognition")
                } else if (currentWord.wordType === "keyWords") {
                    setActiveMode("keyWords")
                }
                // 如果没有 wordType 属性，可以根据 status 来推断
                else if (currentWord.status === "mastered" || currentWord.status === "recognition") {
                    setActiveMode("recognition") // 需会认
                } else {
                    setActiveMode("keyWords") // 需会写（重点词）
                }
            }
        }

        // 检查是否是从其他页面跳转过来的
        if (params) {
            if (params.hideStatusBar) {
                setHideStatusBar(params.hideStatusBar === "true")
            }

            // 检查是否是从计划页面跳转过来的
            if (params.fromPlan) {
                setIsFromPlan(params.fromPlan === "true")
            }
        }
    }, [currentWord, params, isChangingWord, isFromPlan])

    // 返回上一页
    const handleBack = () => {
        router.back()
    }

    // 切换收藏状态
    const toggleFavorite = () => {
        if (isFavorite) {
            // 如果已收藏，则取消收藏
            setIsFavorite(false)
        } else {
            // 如果未收藏，则显示收藏弹窗
            setCollectionModalVisible(true)
        }
    }

    // 下一个单词
    const handleNext = () => {
        if (currentWordIndex < PRACTICE_DATA.length - 1) {
            setIsChangingWord(true)

            // 确保先重置所有状态
            setSelectedParts([])
            setShowHint(false)
            setHintState(0)
            setFeedback({ type: null, message: "" })
            setSelectedOption(null)
            setIsCorrect(null)
            setShowFeedback(false)
            setHasRecording(false)
            setScore(null)
            setIsRecording(false)
            setUserInput("")
            setFeedbackState("none")

            // 添加淡出动画
            RNAnimated.timing(cardOpacity, {
                toValue: 0,
                duration: 250,
                useNativeDriver: true,
            }).start(() => {
                // 更新单词索引和重置步骤
                setCurrentWordIndex(currentWordIndex + 1)
                setCurrentStep(0)
                slideAnim.setValue(0)

                // 添加淡入动画
                setTimeout(() => {
                    RNAnimated.timing(cardOpacity, {
                        toValue: 1,
                        duration: 250,
                        useNativeDriver: true,
                    }).start(() => {
                        setIsChangingWord(false)
                    })
                }, 150) // 稍微延长延迟确保状态已更新
            })
        } else {
            // 已完成所有单词
            setAllWordsCompleted(true)
            setTimeout(() => {
                setAllWordsCompleted(false)
                // 可以选择返回到词汇列表或其他页面
                // router.back()
            }, 3000)
        }
    }

    // 处理步骤变化
    const handleStepChange = (index: number) => {
        // 添加淡出动画
        RNAnimated.timing(cardOpacity, {
            toValue: 0,
            duration: 200,
            useNativeDriver: true,
        }).start(() => {
            // 获取步骤标签
            const stepLabel = STEPS[index].label

            // 获取对应的组件索引，如果没有映射则默认为0
            const stepIndex = STEP_COMPONENTS[stepLabel] !== undefined ? STEP_COMPONENTS[stepLabel] : 0

            // 滑动到对应的组件
            RNAnimated.timing(slideAnim, {
                toValue: -stepIndex * width,
                duration: 300,
                useNativeDriver: true,
            }).start()

            setCurrentStep(index)

            // 添加淡入动画
            setTimeout(() => {
                RNAnimated.timing(cardOpacity, {
                    toValue: 1,
                    duration: 200,
                    useNativeDriver: true,
                }).start()
            }, 50) // 短暂延迟确保状态已更新
        })
    }

    // 上一步
    const handlePrevStep = () => {
        if (currentStep > 0) {
            handleStepChange(currentStep - 1)
        }
    }

    // 下一步
    const handleNextStep = () => {
        if (currentStep < STEPS.length - 1) {
            handleStepChange(currentStep + 1)
        }
    }

    // 学习步骤 - 播放音频
    const handlePlayAudio = (slow = false) => {
        if (slow) {
            setIsSlowPlaying(true)
            setTimeout(() => setIsSlowPlaying(false), 2000)
        } else {
            setIsPlaying(true)
            setTimeout(() => setIsPlaying(false), 2000)
        }
    }

    // 学习步骤 - 更新单词状态
    const handleUpdateStatus = (status: WordStatus) => {
        setWordStatus(status)
    }

    // 朗读步骤 - 开始录音
    const startRecording = () => {
        setIsRecording(true)
        // 开始计时
        recordingTimer.current = setInterval(() => {
            setRecordingDuration((prev) => prev + 1)
        }, 1000)
        // 开始录音动画
        RNAnimated.loop(
            RNAnimated.sequence([
                RNAnimated.timing(recordingPulse, {
                    toValue: 1.2,
                    duration: 1000,
                    useNativeDriver: true,
                }),
                RNAnimated.timing(recordingPulse, {
                    toValue: 1,
                    duration: 1000,
                    useNativeDriver: true,
                }),
            ]),
        ).start()
    }

    // 朗读步骤 - 停止录音
    const stopRecording = () => {
        setIsRecording(false)
        setHasRecording(true)
        // 停止计时
        if (recordingTimer.current) {
            clearInterval(recordingTimer.current)
        }
        setRecordingDuration(0)
        // 停止录音动画
        recordingPulse.setValue(1)
        // 模拟评分
        const randomScore = Math.floor(Math.random() * 5) + 1
        setScore(randomScore)
        // 评分动画
        RNAnimated.spring(scoreScale, {
            toValue: 1,
            friction: 8,
            tension: 40,
            useNativeDriver: true,
        }).start()
    }

    // 朗读步骤 - 播放录音
    const playRecording = () => {
        if (!hasRecording) return
        setIsPlaying(true)
        // 模拟播放
        setTimeout(() => {
            setIsPlaying(false)
        }, 2000)
    }

    // 选择步骤 - 处理选项选择
    const handleOptionSelect = (optionId: string, isCorrect: boolean) => {
        setSelectedOption(optionId)
        setIsCorrect(isCorrect)
        setShowFeedback(true)

        if (isCorrect) {
            // 延迟后自动进入下一步
            setTimeout(() => {
                if (currentStep < STEPS.length - 1) {
                    handleStepChange(currentStep + 1)
                }
            }, 1500)
        }
    }

    // 选择步骤 - 处理正确答案
    const handleCorrectAnswer = () => {
        if (currentStep < STEPS.length - 1) {
            handleStepChange(currentStep + 1)
        }
    }

    // 拆分拼写 - 选择单词部分
    const handlePartSelect = (part: string) => {
        // 检查是否已经选择了这个部分
        const partIndex = selectedParts.indexOf(part)

        if (partIndex !== -1) {
            // 如果已经选择了，则移除它
            const newSelectedParts = [...selectedParts]
            newSelectedParts.splice(partIndex, 1)
            setSelectedParts(newSelectedParts)
            return
        }

        if (selectedParts.length < currentWord.parts.length) {
            const newSelectedParts = [...selectedParts, part]
            setSelectedParts(newSelectedParts)

            // 检查是否已经选择了所有部分，如果是，则验证答案
            if (newSelectedParts.length === currentWord.parts.length) {
                // 检查答案是否正确
                const correct = newSelectedParts.every((part, index) => part === currentWord.parts[index])

                if (correct) {
                    // 如果正确，显示成功反馈
                    setFeedback({ type: "success", message: "拼写正确！" })

                    // 延迟后自动进入下一步
                    setTimeout(() => {
                        setFeedback({ type: null, message: "" })
                        setSelectedParts([])
                        if (currentStep < STEPS.length - 1) {
                            handleStepChange(currentStep + 1)
                        }
                    }, 1200)
                } else {
                    // 如果错误，显示错误反馈
                    setFeedback({ type: "error", message: "拼写错误，请重试" })

                    // 延迟后清空选择
                    setTimeout(() => {
                        setSelectedParts([])
                        setFeedback({ type: null, message: "" })
                    }, 1200)
                }
            }
        }
    }

    // 拆分拼写 - 移除单词部分
    const handlePartRemove = (index: number) => {
        const newSelectedParts = [...selectedParts]
        newSelectedParts.splice(index, 1)
        setSelectedParts(newSelectedParts)
    }

    // 拆分拼写 - 显示提示
    const showSplitHint = () => {
        setShowHint(true)

        // 淡入淡出动画
        RNAnimated.sequence([
            RNAnimated.timing(slotsOpacity, {
                toValue: 0,
                duration: 200,
                useNativeDriver: true,
            }),
            RNAnimated.timing(slotsOpacity, {
                toValue: 1,
                duration: 200,
                useNativeDriver: true,
            }),
        ]).start()

        // 2秒后隐藏提示
        setTimeout(() => {
            setShowHint(false)
        }, 2000)
    }

    // 自然拼读 - 显示提示
    const toggleNaturalHint = () => {
        // 缩放提示按钮
        RNAnimated.sequence([
            RNAnimated.timing(contentOpacity, {
                toValue: 0,
                duration: 200,
                useNativeDriver: true,
            }),
            RNAnimated.timing(contentOpacity, {
                toValue: 1,
                duration: 200,
                useNativeDriver: true,
            }),
        ]).start()

        // 更新提示状态
        setHintState((prev) => (prev + 1) % 3)

        // 如果是显示单词状态
        if (hintState === 1) {
            // 显示单词动画
            RNAnimated.timing(wordOpacity, {
                toValue: 1,
                duration: 300,
                useNativeDriver: true,
            }).start()

            // 3秒后隐藏单词
            setTimeout(() => {
                // 隐藏单词动画
                RNAnimated.timing(wordOpacity, {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                }).start(() => {
                    setHintState(0)
                })
            }, 3000)
        } else if (hintState === 2) {
            // 从显示单词回到无提示
            setHintState(0)

            // 隐藏单词动画
            RNAnimated.timing(wordOpacity, {
                toValue: 0,
                duration: 300,
                useNativeDriver: true,
            }).start()
        }
    }

    // 字母拼写 - 检查答案
    const checkLetterSpell = (isCorrect: boolean) => {
        if (isCorrect) {
            // 如果正确，延迟后自动进入下一步或下一个单词
            setTimeout(() => {
                if (currentStep < STEPS.length - 1) {
                    handleStepChange(currentStep + 1)
                } else {
                    // 如果是最后一个步骤，先重置卡片状态再进入下一个单词
                    cardOpacity.setValue(0) // 确保卡片先隐藏

                    // 延迟一下再切换单词，确保动画顺序正确
                    setTimeout(() => {
                        if (currentWordIndex < PRACTICE_DATA.length - 1) {
                            handleNext()
                        } else {
                            // 如果是最后一个单词的最后一个步骤，显示完成提示
                            setAllWordsCompleted(true)
                            setTimeout(() => {
                                setAllWordsCompleted(false)
                            }, 3000)
                        }
                    }, 100)
                }
            }, 1200)
        }
    }

    // 字母拼写 - 显示提示
    const showLetterHint = () => {
        // 保存当前输入
        const currentInput = userInput

        // 显示正确单词
        setUserInput(currentWord.word)
        setShowHint(true)

        // 2秒后恢复用户输入
        setTimeout(() => {
            setShowHint(false)
            setUserInput(currentInput)
        }, 2000)
    }

    // 准备单词列表数据
    const wordListData = PRACTICE_DATA.map((item) => ({
        id: item.id,
        word: item.word,
        phonetic: item.phonetic,
        meaning: item.meaning,
    }))

    // 处理音素点击
    const handlePhonemePress = (phoneme: string, sound: string) => {
        console.log(`音素: ${phoneme}, 发音: ${sound}`)
    }

    // 步骤标题 - 使用动态步骤
    const STEPS = React.useMemo(() => {
        const steps = isFromPlan ? learningSteps[activeMode] : ["学", "读", "选", "拆分", "拼读", "拼写"]
        return steps.map((step) => ({
            id: step,
            label: step,
        }))
    }, [isFromPlan, learningSteps, activeMode])

    return (
        <View style={styles.container}>
            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                <SafeAreaView style={styles.safeArea} edges={["top"]}>
                    {/* 头部 */}
                    <View style={styles.header}>
                        <View style={styles.headerLeftSection}>
                            <TouchableOpacity onPress={handleBack} style={styles.headerButton}>
                                <ArrowLeft size={24} color={theme.colors.neutral.black} />
                            </TouchableOpacity>
                        </View>

                        <View style={styles.headerTitleContainer}>
                            <Text style={styles.headerTitle}>
                                {isFromPlan
                                    ? activeMode === "keyWords"
                                        ? "重点词"
                                        : "需会认"
                                    : `学练一体(${currentWordIndex + 1}/${PRACTICE_DATA.length})`}
                            </Text>
                        </View>

                        <View style={styles.headerRightSection}>
                            {isFromPlan && (
                                <TouchableOpacity style={styles.headerButton} onPress={() => setSettingsModalVisible(true)}>
                                    <Settings size={24} color={theme.colors.neutral.black} />
                                </TouchableOpacity>
                            )}
                            <TouchableOpacity style={styles.headerButton} onPress={() => setListModalVisible(true)}>
                                <List size={24} color={theme.colors.neutral.black} />
                            </TouchableOpacity>
                        </View>
                    </View>

                    {/* 进度条 */}
                    <ProgressBar current={currentWordIndex + 1} total={PRACTICE_DATA.length} showText={false} />

                    {/* 步骤指示器 - 不滚动的紧凑版本 */}
                    <StepsIndicator steps={STEPS} currentStep={currentStep} onStepChange={handleStepChange} />

                    {/* 内容区域 */}
                    <View style={styles.contentWrapper}>
                        {/* 左侧导航按钮 */}
                        {currentStep > 0 && (
                            <TouchableOpacity style={styles.navButtonLeft} onPress={handlePrevStep}>
                                <ChevronLeft size={24} color={theme.colors.primary.default} />
                            </TouchableOpacity>
                        )}

                        {/* 右侧导航按钮 */}
                        {currentStep < STEPS.length - 1 && (
                            <TouchableOpacity style={styles.navButtonRight} onPress={handleNextStep}>
                                <ChevronRight size={24} color={theme.colors.primary.default} />
                            </TouchableOpacity>
                        )}

                        <RNAnimated.View
                            style={[
                                styles.slidingContainer,
                                {
                                    transform: [{ translateX: slideAnim }],
                                    opacity: cardOpacity,
                                },
                            ]}
                        >
                            {/* 学习步骤 - 使用WordCardContent组件 */}
                            <View style={styles.cardContainer}>
                                <WordCardContent
                                    word={currentWord}
                                    settings={{ translationFontSize: 16, moduleFontSize: 14 }}
                                    isPlaying={isPlaying}
                                    isSlowPlaying={isSlowPlaying}
                                    isRecording={isRecording}
                                    onPlayAudio={handlePlayAudio}
                                    onRecord={startRecording}
                                    onUpdateStatus={handleUpdateStatus}
                                    onToggleFavorite={toggleFavorite}
                                    hideStatusBar={true} // 确保隐藏组件内部的状态栏
                                />
                            </View>

                            {/* 朗读步骤 - 使用ReadingCard组件 */}
                            <View style={styles.cardContainer}>
                                <ReadingCard
                                    word={currentWord.word}
                                    phonetic={currentWord.phonetic}
                                    meaning={currentWord.meaning}
                                    isPlaying={isPlaying}
                                    isRecording={isRecording}
                                    recordingDuration={recordingDuration}
                                    hasRecording={hasRecording}
                                    score={score}
                                    phonemes={currentWord.phonemes}
                                    onPlayAudio={handlePlayAudio}
                                    onStartRecording={startRecording}
                                    onStopRecording={stopRecording}
                                    onPlayRecording={playRecording}
                                    onPhonemePress={handlePhonemePress}
                                />
                            </View>

                            {/* 选择步骤 - 使用ChoiceCard组件 */}
                            <View style={styles.cardContainer}>
                                <ChoiceCard
                                    word={currentWord.word}
                                    phonetic={currentWord.phonetic}
                                    options={currentWord.options}
                                    isPlaying={isPlaying}
                                    onPlayAudio={handlePlayAudio}
                                    onOptionSelect={handleOptionSelect}
                                    onCorrectAnswer={handleCorrectAnswer}
                                />
                            </View>

                            {/* 拆分拼写步骤 */}
                            <View style={styles.cardContainer}>
                                <View style={styles.card}>
                                    <SplitSpellCard
                                        parts={currentWord.parts}
                                        phonetic={currentWord.phonetic}
                                        type={currentWord.type}
                                        meaning={currentWord.meaning}
                                        showHint={showHint}
                                        slotsOpacity={slotsOpacity}
                                        selectedParts={selectedParts}
                                        onPartSelect={handlePartSelect}
                                        onPartRemove={handlePartRemove}
                                        feedback={feedback}
                                        onShowHint={showSplitHint}
                                    />

                                    {/* 提示按钮 */}
                                    <TouchableOpacity style={styles.hintButton} onPress={showSplitHint}>
                                        <Lightbulb size={20} color={theme.colors.primary.default} />
                                        <Text style={styles.hintButtonText}>提示</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>

                            {/* 自然拼读步骤 */}
                            <View style={styles.cardContainer}>
                                <View style={styles.card}>
                                    <NaturalReadingCard
                                        word={currentWord.word}
                                        phonetic={currentWord.phonetic}
                                        type={currentWord.type}
                                        meaning={currentWord.meaning}
                                        parts={currentWord.parts}
                                        showPhonetic={hintState >= 1}
                                        showWord={hintState === 2}
                                        contentOpacity={contentOpacity}
                                        wordOpacity={wordOpacity}
                                        onPartSelect={handlePartSelect}
                                        onPartRemove={handlePartRemove}
                                        selectedParts={selectedParts}
                                        feedback={feedback}
                                        onShowHint={toggleNaturalHint}
                                    />

                                    {/* 提示按钮 */}
                                    <TouchableOpacity style={styles.hintButton} onPress={toggleNaturalHint}>
                                        <Lightbulb size={20} color={theme.colors.primary.default} />
                                        <Text style={styles.hintButtonText}>提示</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>

                            {/* 字母拼写步骤 */}
                            <View style={styles.cardContainer}>
                                <View style={styles.card}>
                                    <LetterSpellCard
                                        word={currentWord.word}
                                        phonetic={currentWord.phonetic}
                                        meaning={currentWord.meaning}
                                        showHint={showHint}
                                        onPlaySound={() => handlePlayAudio()}
                                        onCheckAnswer={checkLetterSpell}
                                        onNext={handleNext}
                                        onShowHint={showLetterHint}
                                    />

                                    {/* 提示按钮 */}
                                    <TouchableOpacity style={styles.hintButton} onPress={showLetterHint}>
                                        <Lightbulb size={20} color={theme.colors.primary.default} />
                                        <Text style={styles.hintButtonText}>提示</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </RNAnimated.View>
                    </View>
                </SafeAreaView>

                {/* 底部状态栏 - 只在非学练一体模式下显示 */}
                {!hideStatusBar && (
                    <View style={styles.bottomBar}>
                        {/* 单词状态选择 - 只在非计划模式下显示 */}
                        {!isFromPlan && (
                            <View style={styles.statusButtons}>
                                <TouchableOpacity
                                    style={[styles.statusButton, wordStatus === "new" && styles.statusButtonActive]}
                                    onPress={() => setWordStatus("new")}
                                >
                                    <Text style={[styles.statusButtonText, wordStatus === "new" && styles.statusButtonTextActive]}>
                                        生词
                                    </Text>
                                </TouchableOpacity>

                                <TouchableOpacity
                                    style={[styles.statusButton, wordStatus === "learning" && styles.statusButtonActive]}
                                    onPress={() => setWordStatus("learning")}
                                >
                                    <Text style={[styles.statusButtonText, wordStatus === "learning" && styles.statusButtonTextActive]}>
                                        学习中
                                    </Text>
                                </TouchableOpacity>

                                <TouchableOpacity
                                    style={[styles.statusButton, wordStatus === "mastered" && styles.statusButtonActive]}
                                    onPress={() => setWordStatus("mastered")}
                                >
                                    <Text style={[styles.statusButtonText, wordStatus === "mastered" && styles.statusButtonTextActive]}>
                                        掌握
                                    </Text>
                                </TouchableOpacity>
                            </View>
                        )}

                        {/* 收藏按钮 */}
                        <TouchableOpacity
                            style={[styles.favoriteButton, isFromPlan && { marginLeft: "auto" }]}
                            onPress={toggleFavorite}
                        >
                            {isFavorite ? (
                                <Bookmark
                                    size={22}
                                    color={theme.colors.secondary.orange.default}
                                    fill={theme.colors.secondary.orange.default}
                                />
                            ) : (
                                <BookmarkPlus size={22} color={theme.colors.neutral.gray} />
                            )}
                        </TouchableOpacity>

                        {/* 下一词按钮 */}
                        <TouchableOpacity style={styles.nextButton} onPress={handleNext}>
                            <LinearGradient
                                colors={theme.colors.primary.gradient}
                                start={{ x: 0, y: 0 }}
                                end={{ x: 1, y: 0 }}
                                style={styles.nextButtonGradient}
                            >
                                <Text style={styles.nextButtonText}>下一词</Text>
                                <ChevronRight size={20} color={theme.colors.neutral.white} />
                            </LinearGradient>
                        </TouchableOpacity>
                    </View>
                )}

                {/* 单词列表弹窗 */}
                <WordListModal
                    visible={listModalVisible}
                    data={wordListData}
                    currentIndex={currentWordIndex}
                    onClose={() => setListModalVisible(false)}
                    onSelectWord={(index) => {
                        // 先重置所有状态
                        setSelectedParts([])
                        setShowHint(false)
                        setHintState(0)
                        setFeedback({ type: null, message: "" })
                        setSelectedOption(null)
                        setIsCorrect(null)
                        setShowFeedback(false)
                        setHasRecording(false)
                        setScore(null)
                        setIsRecording(false)
                        setUserInput("")
                        setFeedbackState("none")

                        // 然后更新索引和重置步骤
                        setCurrentWordIndex(index)
                        setCurrentStep(0)
                        slideAnim.setValue(0)
                        setListModalVisible(false)

                        // 确保动画正确
                        cardOpacity.setValue(0)
                        setTimeout(() => {
                            RNAnimated.timing(cardOpacity, {
                                toValue: 1,
                                duration: 250,
                                useNativeDriver: true,
                            }).start()
                        }, 100)
                    }}
                    title="单词列表"
                />

                {/* 收藏弹窗 */}
                <CollectionModal
                    visible={collectionModalVisible}
                    onClose={() => setCollectionModalVisible(false)}
                    onConfirm={(selectedUnitId, bookId) => {
                        setIsFavorite(true)
                        setCollectionModalVisible(false)
                        // 这里可以添加将单词添加到收藏夹的逻辑
                        console.log("添加到收藏夹", selectedUnitId, bookId)
                    }}
                />

                {/* 完成所有单词的提示 */}
                {allWordsCompleted && (
                    <View style={styles.completionOverlay}>
                        <View style={styles.completionCard}>
                            <Text style={styles.completionTitle}>恭喜！</Text>
                            <Text style={styles.completionText}>您已完成所有单词的学习</Text>
                        </View>
                    </View>
                )}
                {/* 学习设置弹窗 */}
                <LearningSettingsModal
                    visible={settingsModalVisible}
                    onClose={() => setSettingsModalVisible(false)}
                    onConfirm={(steps) => {
                        // 保存当前步骤列表，用于后续比较
                        const currentStepsList = activeMode === "keyWords" ? learningSteps.keyWords : learningSteps.recognition

                        // 更新学习步骤
                        setLearningSteps(steps)

                        // 获取新的步骤列表
                        const newStepsList = activeMode === "keyWords" ? steps.keyWords : steps.recognition

                        // 如果新步骤列表的第一个步骤与当前步骤列表的第一个步骤不同，
                        // 或者当前步骤不在新的步骤列表中，则切换到新列表的第一个步骤
                        if (
                            newStepsList[0] !== currentStepsList[0] ||
                            (STEPS[currentStep] && !newStepsList.includes(STEPS[currentStep].label))
                        ) {
                            // 设置为新步骤列表的第一个步骤
                            setCurrentStep(0)

                            // 获取新的第一个步骤对应的组件索引
                            const newFirstStepLabel = newStepsList[0]
                            const stepIndex =
                                STEP_COMPONENTS[newFirstStepLabel] !== undefined ? STEP_COMPONENTS[newFirstStepLabel] : 0

                            // 更新滑动位置到对应的组件
                            slideAnim.setValue(-stepIndex * width)

                            // 添加淡出淡入动画效果，使过渡更平滑
                            cardOpacity.setValue(0)
                            setTimeout(() => {
                                RNAnimated.timing(cardOpacity, {
                                    toValue: 1,
                                    duration: 250,
                                    useNativeDriver: true,
                                }).start()
                            }, 100)
                        }

                        setSettingsModalVisible(false)
                    }}
                    currentStep={STEPS[currentStep]?.label}
                    initialSteps={learningSteps}
                />
            </LinearGradient>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
        backgroundColor: "#F5F7FF",
    },
    safeArea: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
    },
    headerLeftSection: {
        flexDirection: "row",
        alignItems: "center",
        width: 40,
    },
    headerRightSection: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "flex-end",
        gap: theme.spacing.sm,
    },
    headerTitleContainer: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
        position: "absolute",
        left: 0,
        right: 0,
        textAlign: "center",
    },
    headerButtons: {
        flexDirection: "row",
        gap: theme.spacing.sm,
    },
    headerButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    headerTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
    },
    // 紧凑的步骤指示器
    contentWrapper: {
        flex: 1,
        position: "relative",
        paddingTop: theme.spacing.md,
    },
    slidingContainer: {
        flexDirection: "row",
        width: width * 6, // 6个步骤
        flex: 1,
        marginBottom: 30,
    },
    cardContainer: {
        width: width,
        flex: 1,
    },
    card: {
        width: width - theme.spacing.lg * 2,
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge,
        padding: theme.spacing.xl,
        marginHorizontal: theme.spacing.lg,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    navButtonLeft: {
        position: "absolute",
        left: 0,
        top: "50%",
        width: 44,
        height: 120,
        borderTopRightRadius: 22,
        borderBottomRightRadius: 22,
        backgroundColor: "rgba(255, 255, 255, 0.9)",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 10,
        transform: [{ translateY: -60 }],
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 2, height: 0 },
                shadowOpacity: 0.5,
                shadowRadius: 4,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    navButtonRight: {
        position: "absolute",
        right: 0,
        top: "50%",
        width: 44,
        height: 120,
        borderTopLeftRadius: 22,
        borderBottomLeftRadius: 22,
        backgroundColor: "rgba(255, 255, 255, 0.9)",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 10,
        transform: [{ translateY: -60 }],
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: -2, height: 0 },
                shadowOpacity: 0.5,
                shadowRadius: 4,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    bottomBar: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingTop: theme.spacing.lg,
        paddingBottom: Platform.OS === "ios" ? 34 : theme.spacing.lg,
        backgroundColor: theme.colors.neutral.white,
        borderTopWidth: 1,
        borderTopColor: "rgba(0, 0, 0, 0.05)",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.05)",
                shadowOffset: { width: 0, height: -2 },
                shadowOpacity: 1,
                shadowRadius: 4,
            },
            android: {
                elevation: 8,
            },
        }),
    },
    statusButtons: {
        flexDirection: "row",
        gap: theme.spacing.xs,
    },
    statusButton: {
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.xs,
        borderRadius: theme.borderRadius.medium,
        backgroundColor: theme.colors.neutral.lightGray,
    },
    statusButtonActive: {
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        borderWidth: 1,
        borderColor: theme.colors.primary.default,
    },
    statusButtonText: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.darkGray,
    },
    statusButtonTextActive: {
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    favoriteButton: {
        width: 36,
        height: 36,
        borderRadius: 18,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
        marginHorizontal: theme.spacing.md,
    },
    nextButton: {
        flex: 1,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        height: 44,
    },
    nextButtonGradient: {
        flex: 1,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        gap: theme.spacing.xs,
    },
    nextButtonText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.white,
    },
    // 提示按钮
    hintButton: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        marginTop: theme.spacing.lg,
        padding: theme.spacing.sm,
        borderRadius: theme.borderRadius.large,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignSelf: "center",
    },
    hintButtonText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        marginLeft: theme.spacing.xs,
    },
    completionOverlay: {
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: "rgba(0, 0, 0, 0.5)",
        justifyContent: "center",
        alignItems: "center",
        zIndex: 100,
    },
    completionCard: {
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.xl,
        alignItems: "center",
        justifyContent: "center",
        width: "80%",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.2)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.5,
                shadowRadius: 8,
            },
            android: {
                elevation: 8,
            },
        }),
    },
    completionTitle: {
        fontSize: theme.fontSize.xl,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        marginBottom: theme.spacing.md,
    },
    completionText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        textAlign: "center",
    },
})

